package com.ziytek.web.citizen.service.impl;

import com.ziytek.web.citizen.configuration.db.DDS;
import com.ziytek.web.citizen.constant.DdsConstant;
import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.constant.ServerConstant;
import com.ziytek.web.citizen.constant.SettingConstant;
import com.ziytek.web.citizen.enums.ResponseEnum;
import com.ziytek.web.citizen.mapper.LoginMapper;
import com.ziytek.web.citizen.model.rsp.LogInResponse;
import com.ziytek.web.citizen.pojo.basic.UserLogin;
import com.ziytek.web.citizen.service.itf.LoginService;
import com.ziytek.web.citizen.util.AccessToken;
import com.ziytek.web.citizen.util.TokenUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author fenghx
 * @version 1.0
 * @className LoginServiceImpl
 * Description:
 * @date 2024/3/11 18:32
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LoginServiceImpl implements LoginService {
    private final LoginMapper loginMapper;

    @Override
    @DDS(DdsConstant.DS_BASIC)
    public LogInResponse login(String userName, String password) {
        var response = new LogInResponse();
        response.setRetCode(ServerConstant.ERROR);
        if (Objects.isNull(userName) || Objects.isNull(password)) {
            response.resultError(ResponseEnum.PARAMETER_ERROR.getCode());
            return response;
        }

        var login = loginMapper.findByUserNameAndAvailableOrderByCreateTimeDesc(userName, SettingConstant.IS_AVAILABLE);
        if (login == null) {
            response.resultError(ResponseEnum.USER_NOT_EXIST.getCode());
            return response;
        }

        // 密码不正确
        if (!password.equalsIgnoreCase(login.getUserPassword())) {
            response.resultError(ResponseEnum.PASSWORD_ERROR.getCode());
            return response;
        }

        var token = TokenUtils.getAccessToken(login.getUserName(), login.getUserName());
        var retToken = token != null ? token.getToken() : null;
        if (Objects.nonNull(retToken)) {
            // todo 记录 登录操作日志

            // 更新登录时间及登录信息
            login.setLastLoginInTime(System.currentTimeMillis());
            login.setUpdateTime(System.currentTimeMillis());
            loginMapper.updateDataById(login.getId(), login.getUpdateTime(), login.getLastLoginInTime(), login.getLastLoginOutTime());
        }

        response.resultSuccess(retToken, login.getRole());
        response.setRetMsg("登录成功");
        return response;
    }

    @Override
    @DDS(DdsConstant.DS_BASIC)
    public boolean logOut(String token) {
        AccessToken accessToken = TokenUtils.getAccessToken(token);
        if (accessToken == null) {
            return false;
        }

        // todo 记录 退出操作日志

        var login = loginMapper.findByUserNameAndAvailableOrderByCreateTimeDesc(accessToken.getUserId(), SettingConstant.IS_AVAILABLE);
        if (login == null) {
            return false;
        }

        // 更新登录时间及登录信息
        login.setLastLoginOutTime(System.currentTimeMillis());
        login.setUpdateTime(System.currentTimeMillis());
        loginMapper.updateDataById(login.getId(), login.getUpdateTime(), login.getLastLoginInTime(), login.getLastLoginOutTime());

        return true;
    }

    @Override
    @DDS(DdsConstant.DS_BASIC)
    public int addLogin(UserLogin user) {
        try {
            var id = loginMapper.queryMaxId();
            user.setId(id == null ? NumConstant.INT_ONE : id);
            loginMapper.addUser(user);
        } catch (Exception e) {
            log.error("addUser error:", e);
            return NumConstant.INT_ZERO;
        }
        return NumConstant.INT_ONE;
    }

    @Override
    @DDS(DdsConstant.DS_BASIC)
    public int deleteLogin(UserLogin user) {
        try {
            var oldUser = loginMapper.findById(user.getId());
            if (oldUser == null) {
                return NumConstant.INT_LT_ZERO;
            }

            //loginMapper.deleteUser(SettingConstant.IS_NOT_AVAILABLE, System.currentTimeMillis(), user.getId());
            loginMapper.deleteUserById(oldUser.getId());
        } catch (Exception e) {
            log.error("deleteLogin error:", e);
            return NumConstant.INT_ZERO;
        }
        return NumConstant.INT_ONE;
    }
}
